package com.example.springstudy.controller;

import com.example.springstudy.base.Result;
import com.example.springstudy.base.annotation.SaveLog;
import com.example.springstudy.dao.dbo.MenuInfo;
import com.example.springstudy.entity.Menu;
import com.example.springstudy.mapper.MenuMapper;
import com.example.springstudy.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/menu")
public class MenuController {

    @Autowired
    MenuService menuService;

    @Autowired
    MenuMapper menuMapper;

    @GetMapping("/menus")
    public Result<?> getMenus(){
        List<Menu> menus = menuService.listMenus();
        return Result.success(menus);
    }

    @GetMapping("/list")
    public Result<?> listMenus(@RequestParam int page, @RequestParam(defaultValue = "20") int size) {
        List<MenuInfo> menus = menuService.listMenusByPage(page, size);
        return Result.success(menus);
    }

    @SaveLog("更新新或添加菜单")
    @PostMapping("/addMenu")
    public Result<?> addMenu(@RequestBody Menu menu){
        try {
            boolean ok = menuService.addMenu(menu);
            return Result.success(ok);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    @SaveLog("删除菜单")
    @DeleteMapping("/delete")
    public Result<Boolean> deleteMenu(@RequestParam int menuId){
        return Result.success(menuService.deleteMenu(menuId));
    }

    @GetMapping("/roleMenus")
    public Result<?> getMenusByRole(@RequestParam int roleId){
        List<Integer> menuIds = menuMapper.getMenusByRole(roleId);
        return Result.success(menuIds);
    }
}
